﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KamLib;


namespace Ext.Net.UIS
{

    public class TermNodeFactory
    {

        public static TermNode NewFormNode(Context context, TermNode parent, Term term)
        {
            if (term == null)
                throw new ArgumentNullException("term");

            var editor = NewFormEditor(context, parent, term);
            if (editor == null || !editor.MustMerge(parent)) 
                parent = new TermNode(context, parent, term) { Editor = editor };

            foreach (var term2 in term.Items)
            {
                NewFormNode(context, parent, term2);
            }

            return parent;
        }

        private static TermEditor NewFormEditor(Context context, TermNode parent, Term term)
        {
            if (term.EditorName.yes())
                return TermEditor.FormGet(term.EditorName);

            if (term.LookupEntity != null)
                return LookupEditor.Default;

            var type = term.DataType;
            if (type != null && term.Items.Count == 0)
            {
                if (type.IsAssignableFrom(typeof(bool)))
                    return BoolFieldEditor.Default;
                if (type.IsAssignableFrom(typeof(int)))
                    return NumberFieldEditor.Default;
                return TextFieldEditor.Default;
            }

            if (term.IsGroup() || term.IsComposite())
                return FieldSetEditor.Default;
            if (term.IsRow() )
                return FieldRowEditor.Default;
            if (term.IsUnion())
                return FieldUnionEditor.Default;
            if (term.IsLabel())
                return DisplayFieldEditor.Default;


            return null;
        }



        public static TermNode NewGridNode(Context context, TermNode parent, Term term)
        {
            if (term == null)
                throw new ArgumentNullException("term");

            var node = new TermNode(context, parent, term) { Editor = GridEditor.Default };

            return node;
        }

    }

}
